﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using Emc.Documentum.FS.Services.Core;
using Emc.Documentum.FS.DataModel.Core;
using Emc.Documentum.FS.DataModel.Core.Query;
using Emc.Documentum.FS.DataModel.Core.Properties;
using Emc.Documentum.FS.DataModel.Core.Profiles;
using Emc.Documentum.FS.Runtime;
using Emc.Documentum.FS.Runtime.Context;
using Emc.Documentum.FS.DataModel.Core.Context;
using Emc.Documentum.FS.DataModel.Core.Content;

using System.Diagnostics;
using System.IO;
using System.Configuration;

namespace DL_Monster_Mash_WCF_Streamed
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class MonsterMashStreamingService : IMonsterMashStreamingService
    {

        private string defaultRepository = null;
        private string secondaryRepository = null;
        private string userName = null;
        private string password = null;
        private IServiceContext serviceContext;
        private IObjectService objectService;
        private IQueryService queryService;

        public MonsterMashStreamingService()
        {
            Trace.WriteLine("MonsterMashStreamingService: Default Constructor.");
            initializeContext();
        }

        private void initializeContext()
        {
            //grab values from associated config file:
            defaultRepository = ConfigurationManager.AppSettings["Repository"];
            secondaryRepository = ConfigurationManager.AppSettings["Repository"];
            userName = ConfigurationManager.AppSettings["DctmUser"];
            password = ConfigurationManager.AppSettings["DctmPassword"];

            ContextFactory contextFactory = ContextFactory.Instance;
            serviceContext = contextFactory.NewContext();

            RepositoryIdentity repoId = new RepositoryIdentity();
            RepositoryIdentity repositoryIdentity =
                new RepositoryIdentity(defaultRepository, userName, password, "");
            serviceContext.AddIdentity(repositoryIdentity);

            ContentTransferProfile contentTransferProfile = new ContentTransferProfile();
            contentTransferProfile.TransferMode = ContentTransferMode.MTOM;
            contentTransferProfile.Geolocation = "Toronto";
            serviceContext.SetProfile(contentTransferProfile);

            if (!String.IsNullOrEmpty(secondaryRepository))
            {
                RepositoryIdentity repoId1 = new RepositoryIdentity();
                repoId1.RepositoryName = secondaryRepository;
                repoId1.UserName = userName;
                repoId1.Password = password;
                serviceContext.AddIdentity(repoId1);
            }
        }


        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }

        //public StreamedDocumentumObject GetDocumentumObject(String sQualifier)
        //{
        //    if (String.IsNullOrEmpty(sQualifier))
        //    {
        //        return null;
        //    }

        //    Trace.WriteLine("Inside GetObjectFromDocumentum...");

        //    StreamedDocumentumObject repositoryObj = null;

        //    initializeContext();

        //    ContentTransferProfile profile = new ContentTransferProfile();
        //    profile.TransferMode = ContentTransferMode.MTOM;
        //    serviceContext.SetProfile(profile);

        //    ServiceFactory serviceFactory = ServiceFactory.Instance;
        //    objectService = serviceFactory.GetRemoteService<IObjectService>(serviceContext);
        //    queryService = serviceFactory.GetRemoteService<IQueryService>(serviceContext);

        //    ContentProfile contentProfile = new ContentProfile();
        //    contentProfile.FormatFilter = FormatFilter.ANY;

        //    OperationOptions operationOptions = new OperationOptions();
        //    operationOptions.ContentProfile = contentProfile;

        //    try
        //    {
        //        ObjectIdentitySet objIdentitySet = new ObjectIdentitySet();
        //        ObjectIdentity objIdentity = new ObjectIdentity();
        //        objIdentity.RepositoryName = defaultRepository;
        //        Qualification objQualifier = new Qualification(sQualifier);
        //        objIdentity.Value = objQualifier;
        //        objIdentity.ValueType = ObjectIdentityType.QUALIFICATION;
        //        objIdentitySet.AddIdentity(objIdentity);

        //        DataPackage dataPackage = objectService.Get(objIdentitySet, operationOptions);

        //        Emc.Documentum.FS.DataModel.Core.DataObject myObj = dataPackage.DataObjects[0];

        //        Emc.Documentum.FS.DataModel.Core.Content.Content myContent = myObj.Contents[0];
        //        repositoryObj = new StreamedDocumentumObject(myObj.Identity.GetValueAsString(), myContent.GetAsByteArray());

        //    }
        //    catch (ServiceException servex)
        //    {
        //    }
        //    catch (Exception ex)
        //    {
        //    }

        //    Trace.Flush();
        //    Trace.Close();

        //    return repositoryObj;


        //}

        public String[] GetListOfContentObjects(String sQualifier)
        {
            if (String.IsNullOrEmpty(sQualifier))
            {
                return null;
            }

            initializeContext();

            List<String> allObjIDs = new List<String>();

            ContentTransferProfile profile = new ContentTransferProfile();
            profile.TransferMode = ContentTransferMode.MTOM;
            serviceContext.SetProfile(profile);

            ServiceFactory serviceFactory = ServiceFactory.Instance;
            queryService = serviceFactory.GetRemoteService<IQueryService>(serviceContext);

            ContentProfile contentProfile = new ContentProfile();
            contentProfile.FormatFilter = FormatFilter.ANY;

            OperationOptions operationOptions = new OperationOptions();
            operationOptions.ContentProfile = contentProfile;

            try
            {
                PassthroughQuery query = new PassthroughQuery();
                query.AddRepository(defaultRepository);
                query.QueryString = sQualifier;
                QueryExecution queryExec = new QueryExecution(0, 4, 4);
                QueryResult allObjects = queryService.Execute(query, queryExec, operationOptions);

                String modelID = null;

                if (allObjects.DataObjects.Count() != 1)
                {
                    return null;
                }

                modelID = allObjects.DataObjects[0].Identity.GetValueAsString();

                allObjIDs.Add(modelID);

                ObjectIdentity objId = new ObjectIdentity(defaultRepository);
                objId.Value = new ObjectId(modelID);
                objId.ValueType = ObjectIdentityType.OBJECT_ID;

                objectService = serviceFactory.GetRemoteService<IObjectService>(serviceContext);

                ObjectIdentitySet idSet = new ObjectIdentitySet(objId);

                DataPackage modelObjects = objectService.Get(idSet, operationOptions);

                if (modelObjects.DataObjects.Count() != 1)
                {
                    return null;
                }

                DataObject modelObject = modelObjects.DataObjects[0];

                PropertySet modelAttrs = modelObject.Properties;
                StringArrayProperty v_textures = (StringArrayProperty)modelAttrs.Get("v_textures");

                foreach (String textureId in v_textures.Values)
                {
                    allObjIDs.Add(textureId);
                }

            }
            catch (ServiceException servex)
            {
            }
            catch (Exception ex)
            {
            }

            return allObjIDs.ToArray();


        }

        public Byte[] GetDocumentumContent(String objectID)
        {

            if (String.IsNullOrEmpty(objectID))
            {
                return null;
            }

            Byte[] repositoryObj = null;

            initializeContext();

            ContentTransferProfile profile = new ContentTransferProfile();
            profile.TransferMode = ContentTransferMode.MTOM;
            serviceContext.SetProfile(profile);

            ServiceFactory serviceFactory = ServiceFactory.Instance;
            objectService = serviceFactory.GetRemoteService<IObjectService>(serviceContext);
            queryService = serviceFactory.GetRemoteService<IQueryService>(serviceContext);

            ContentProfile contentProfile = new ContentProfile();
            contentProfile.FormatFilter = FormatFilter.ANY;

            OperationOptions operationOptions = new OperationOptions();
            operationOptions.ContentProfile = contentProfile;

            try
            {
                ObjectIdentitySet objIdentitySet = new ObjectIdentitySet();
                ObjectIdentity objIdentity = new ObjectIdentity();
                objIdentity.RepositoryName = defaultRepository;
                ObjectId objQualifier = new ObjectId(objectID);
                objIdentity.Value = objQualifier;
                objIdentity.ValueType = ObjectIdentityType.OBJECT_ID;
                objIdentitySet.AddIdentity(objIdentity);

                DataPackage dataPackage = objectService.Get(objIdentitySet, operationOptions);

                Emc.Documentum.FS.DataModel.Core.DataObject myObj = dataPackage.DataObjects[0];

                Emc.Documentum.FS.DataModel.Core.Content.Content myContent = myObj.Contents[0];

                repositoryObj = myContent.GetAsByteArray();

            }
            catch (ServiceException servex)
            {
            }
            catch (Exception ex)
            {
            }

            return repositoryObj;
        }

        public DocumentumObject[] GetListOfRepositoryObjects(String sQualifier)
        {
            if (String.IsNullOrEmpty(sQualifier))
            {
                return null;
            }

            initializeContext();

            List<DocumentumObject> allModelObjects = new List<DocumentumObject>();

            ContentTransferProfile profile = new ContentTransferProfile();
            profile.TransferMode = ContentTransferMode.MTOM;
            serviceContext.SetProfile(profile);

            ServiceFactory serviceFactory = ServiceFactory.Instance;
            queryService = serviceFactory.GetRemoteService<IQueryService>(serviceContext);

            ContentProfile contentProfile = new ContentProfile();
            contentProfile.FormatFilter = FormatFilter.ANY;

            OperationOptions operationOptions = new OperationOptions();
            operationOptions.ContentProfile = contentProfile;

            try
            {
                PassthroughQuery query = new PassthroughQuery();
                query.AddRepository(defaultRepository);
                query.QueryString = sQualifier;
                QueryExecution queryExec = new QueryExecution(0, 4, 4);
                QueryResult allObjects = queryService.Execute(query, queryExec, operationOptions);

                String modelID = null;

                if (allObjects.DataObjects.Count() == 0)
                {
                    return null;
                }


                foreach (DataObject returnedObject in allObjects.DataObjects)
                {
                    modelID = returnedObject.Identity.GetValueAsString();
                    StringProperty objName = (StringProperty)returnedObject.Properties.Get("object_name");
                    DocumentumObject currObject = new DocumentumObject();
                    currObject.ID = modelID;
                    currObject.Name = objName.Value;
                    allModelObjects.Add(currObject);
                }




            }
            catch (ServiceException servex)
            {
            }
            catch (Exception ex)
            {
            }

            return allModelObjects.ToArray();


        }

    }
}
